#!/bin/bash
 
tar xzf openssl-3.0.7.tar.gz
 
source ./build_env.sh
 
INSTALL_DIR=$BUILD_DIR/openssl
 
if [ ! -d $INSTALL_DIR ]; then
    mkdir -p $INSTALL_DIR
fi
 
cd openssl-3.0.7
 
function build_device() {
    make distclean
    
    ARCH=$1
    PLATFORM="iphoneos"
    SDK_PATH=$(xcrun -sdk $PLATFORM --show-sdk-path)
    
    export CC=$(xcrun -sdk $PLATFORM -find clang)
    export CFLAGS="-arch $ARCH -isysroot $SDK_PATH -miphoneos-version-min=$IPHONEOS_DEPLOYMENT_TARGET"
    export AR=$(xcrun -sdk $PLATFORM -find ar)
    export RANLIB=$(xcrun -sdk $PLATFORM -find ranlib)
    
    ./Configure ios64-cross no-unit-test no-shared --prefix=$INSTALL_DIR/$ARCH
    
    make -j8
    make install_sw
    make distclean
}

function build_simulator() {
    make distclean
    
    ARCH=$1
    PLATFORM="iphonesimulator"
    SDK_PATH=$(xcrun -sdk $PLATFORM --show-sdk-path)
    
    export CC=$(xcrun -sdk $PLATFORM -find clang)
    export CFLAGS="-arch $ARCH -isysroot $SDK_PATH -miphonesimulator-version-min=$IPHONEOS_DEPLOYMENT_TARGET"
    export AR=$(xcrun -sdk $PLATFORM -find ar)
    export RANLIB=$(xcrun -sdk $PLATFORM -find ranlib)
    
    ./Configure iossimulator-xcrun no-unit-test no-shared --prefix=$INSTALL_DIR/$ARCH
    
    make -j8
    make install_sw
    make distclean
}

# 编译各个架构 - 只编译arm64和x86_64
build_device arm64
build_simulator x86_64

# 创建通用库
UNIVERSAL_DIR=$INSTALL_DIR/universal
mkdir -p $UNIVERSAL_DIR/lib
mkdir -p $UNIVERSAL_DIR/include

cp -R $INSTALL_DIR/arm64/include/* $UNIVERSAL_DIR/include/

# 合并所有架构的库文件
lipo -create \
    $INSTALL_DIR/arm64/lib/libssl.a \
    $INSTALL_DIR/x86_64/lib/libssl.a \
    -output $UNIVERSAL_DIR/lib/libssl.a

lipo -create \
    $INSTALL_DIR/arm64/lib/libcrypto.a \
    $INSTALL_DIR/x86_64/lib/libcrypto.a \
    -output $UNIVERSAL_DIR/lib/libcrypto.a
 
cd ..
 
rm -rf openssl-3.0.7